import { ref, computed, onMounted, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import * as CONFIG from '@/pages/home/views/sale/config/order'

export const useOrderStore = defineStore('order', () => {
  const orderList = ref([])
  const date = new Date();
  const dateAfterWeek = new Date().getTime() + 60 * 60 * 1000 * 24 * 7
  const sku = ref<Sku>({
    no: 0,
    skuId: 0,
    skuName: "",
    skuBrand: "",
    internalBrand: "",
    specification: "",
    quantity: null,
    unit: "",
    byQuantity: "",
    weight: null,
    unitPrice: null,
    amount: null,
    actualDeliver: 0,
    oweDeliver: null,
    orderState: "待送货",
    skuType: "板",
    specLength: null,
    specWidth: null,
    specThickness: null,
    specDiameter: null,
    specInnerD: null,
    specEccentricD: null,
    specOtherSpec: null,
    isEstimate: 0,
    operationType: "add",
    otherSpecs: {},
    completeDt: ""
  })
  const order = ref<Order>({
    orderId: "",
    clientName: "",
    clientCode: "",
    skuList: [{ ...sku.value }],
    scheduledDt: new Date(dateAfterWeek).toJSON().slice(0, 10),
    remark: "",
    orderDt:`${date.getFullYear()}-${('0'+(date.getMonth()+1)).slice(-2)}-${('0'+date.getDate()).slice(-2)}`,
  })

  const validateForm = (rule, value, callback) => {
    let field = rule.field.split('.')[2]
    switch(field){
      case "quantity":
        field = "订单量"
        break
      case "unitPrice":
        field = "订货单价"
        break
      case "amount":
        field = "订货金额"
        break
      case "specLength":
        field = "规格参数-长"
        break
      case "specWidth":
        field = "规格参数-宽"
        break
      case "specThickness":
        field = "规格参数-厚"
        break
      case "specDiameter":
        field = "规格参数-直/外径"
        break
      case "specInnerD":
        field = "规格参数-内径"
        break
    }
    if(!value){
      callback(new Error(`${field}不能为空`))
    }
    else if(!Number.isFinite(Number(value))){
      callback(new Error(`${field}必须为数值`))
    }
    else if(Number(value) <= 0){
      callback(new Error(`${field}必须大于 0`))
    }
    else callback()
  }
  const orderRules = ref({
    clientName: [
      { required: true, message: '请选择客户', trigger: 'change' },
    ],
    clientCode: [
      { required: true, message: '请选择客户代号', trigger: 'change' },
    ],
    orderDt: [
      { type: 'date', required: true, message: '请选择下单日期', trigger: 'change' },
    ],
    scheduledDt: [
      { type: 'date', required: true, message: '请选择要求送达日期', trigger: 'change' },
    ],
    skuName: [
      { required: true, message: '请选择商品', trigger: 'change' },
    ],
    skuBrand: [
      { required: true, message: '请选择牌号/款式', trigger: 'change' },
    ],
    internalBrand: [
      { required: true, message: '请选择内部牌号', trigger: 'change' },
    ],
    skuType: [
      { required: true, message: '请选择商品类型', trigger: 'change' },
    ],
    specification: [
      { required: true, message: '请选择规格型号', trigger: 'change' },
    ],
    specLength: [
      { required: true, message: '规格型号-长不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specWidth: [
      { required: true, message: '规格型号-宽不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specThickness: [
      { required: true, message: '规格型号-厚不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specDiameter: [
      { required: true, message: '规格型号-直径/外径不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specInnerD: [
      { required: true, message: '规格型号-内径不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specEccentricD: [
      { required: true, message: '规格型号-偏心直径不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' },
    ],
    specOtherSpec: [
      { 
        validator: (rule, value, callback) => {
          if(!value) callback()
          else if(!Number.isFinite(Number(value))){
            callback(new Error('该规格参数必须为数值'))
          }
          else if(Number(value) <= 0){
            callback(new Error('该规格参数必须大于 0'))
          }
          else callback()
        },
        trigger: 'change'
      },
    ],
    unit: [
      { required: true, message: '请选择单位', trigger: 'change' },
    ],
    quantity: [
      { required: true, message: '订单量不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' }
    ],
    byQuantity: [
      { required: true, message: '请选择是否按数量', trigger: 'change' }
    ],
    weight: [
      { type: 'number', 
        message: '订货重量必须为数值', 
        trigger: 'change', 
        transform: (value) => Number(value)
      },
    ],
    unitPrice: [
      { required: true, message: '订货单价不能为空', trigger: 'change' },
      { validator: validateForm, trigger: 'change' }
    ],
    amount: [
      // { required: true, message: '订单总金额不能为空', trigger: 'change' },
      // { validator: validateForm, trigger: 'change' }
    ]
  })  
  const orderData = ref<Order[]>([])

  const allSpecification = ref([])

  const editOrder = (val) => {
    order.value = JSON.parse(JSON.stringify(val))
    order.value.skuList && order.value.skuList.length > 0 && order.value.skuList.forEach((sku) => {
      const matchType = sku.skuName.match(CONFIG.SKU_SPEC.SPEC_DETECTION)
      if(matchType){
        sku.skuType = matchType[1]
        sku.specDiameter = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_1)?.[1]
        sku.specInnerD = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_2)?.[1]
        sku.specLength = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_3)?.[1]
        sku.specWidth = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_4)?.[1]
        sku.specThickness = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_5)?.[1]
        sku.specEccentricD = sku.specification.match(CONFIG.SKU_SPEC.SPEC_REGEX_6)?.[1]
      }
      else {
        sku.skuType = "其他"
        sku.specOtherSpec = sku.specification
      }
    })
  }
  const resetOrder = (formRef) => {
    formRef.value.resetFields()
    order.value.orderId = ""
    order.value.clientCode = ""
    order.value.skuList = [{ ...sku.value }]
  }
  const getOrderList = async () => {
    console.log("getOrderList")
    let tableList = []
    orderData.value && orderData.value.length > 0 && orderData.value.forEach((order) => {
      order.skuList.forEach((sku) => {
        sku.byQuantity = sku.byQuantity === "true" ? "1" : "0"
        tableList.push({
          orderId: order.orderId,
          clientName: order.clientName,
          clientCode: order.clientCode,
          no: sku.no,
          skuId: sku.skuId,
          skuName: sku.skuName,
          skuBrand: sku.skuBrand,
          internalBrand: sku.internalBrand,
          specification: sku.specification,
          quantity: sku.quantity,
          unit: sku.unit,
          byQuantity: sku.byQuantity,
          weight: sku.weight,
          unitPrice: sku.unitPrice,
          amount: sku.amount,
          actualDeliver: sku.actualDeliver,
          oweDeliver: sku.oweDeliver,
          orderState: sku.orderState,
          isEstimate: sku.isEstimate,
          orderDt: order.orderDt,
          scheduledDt: order.scheduledDt,
          completeDt: sku.completeDt,
          remark: order.remark
        })
      })
    })
    orderList.value = tableList
  }
  const addSku = () => {
    order.value.skuList.push({ ...sku.value, otherSpecs: {} })
  }

  watchEffect(() => {
    order.value.skuList.map((item, index) => {
      if(item.unit === "kg" && item.byQuantity === "0"){
        if(item.weight && item.unitPrice){
          item.amount = Number((item.weight * item.unitPrice).toFixed(2))
        }
        else item.amount = NaN
      }
      else if(item.unit === "pcs"){
        if(item.byQuantity === "1"){
          if(item.quantity && item.unitPrice){
            item.amount = Number((item.quantity * item.unitPrice).toFixed(2))
          }
          else item.amount = NaN
        }
        else if(item.weight && item.unitPrice){
          item.amount = Number((item.weight * item.unitPrice).toFixed(2))
        }
        else item.amount = NaN
      }
      else item.amount = NaN
    })
  })

  return {
    sku,
    order,
    orderList,
    orderData,
    orderRules,
    allSpecification,
    editOrder,
    resetOrder,
    getOrderList,
    addSku
  }
})

interface Order {
  // no: number,
  orderId: string,
  clientName: string,
  clientCode: string,
  orderDt: string,
  scheduledDt: string,
  remark: string,
  skuList: Sku[]
}

interface Sku {
  no: number,
  skuId:number,
  skuName: string,
  skuBrand: string,
  internalBrand: string,
  specification: string,
  quantity: number,
  // returnedQuantity: number,
  unit: string,
  byQuantity: string,
  weight: number,
  unitPrice: number,
  amount: number,
  // refundAmount: number,
  actualDeliver: number,
  oweDeliver: number,
  orderState: string,
  skuType: string,
  specLength: string,
  specWidth: string,
  specThickness: string,
  specDiameter: string,
  specInnerD: string,
  specEccentricD: string,
  specOtherSpec: string,
  isEstimate: number,
  operationType: string,
  otherSpecs: object,
  completeDt: string
}